import os, glob, sys, datetime
import xml.dom.minidom, sys, re
from openpyxl import Workbook

__all__ = ['ExtractStartS_CM4']
def get_irqname_from_hfile(hfile_path:str) -> dict:
    
    if os.path.exists(hfile_path) == False:
        print(f"[Error]Fail to find {hfile_path}!!! \n")
        return None
    
    with open(hfile_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 获取 “typedef enum {\n”和“} IRQn_Type;\n”这两行之前所有的行
    enum_begin = False
    irq_names = []

    irqs = {}
    for i, line in enumerate(lines):
        if enum_begin == False and "typedef enum {" in line:
            enum_begin = True
            continue
        elif "} IRQn_Type;" in line:
            break
                
        if enum_begin == False:
            continue        
        if line.find("=") == -1:
            continue
        if line.startswith("/*"):
            continue
        
        """
        'DMA_IRQn                  =  24               /*!< 24 DMA                                                                    */\n'
        """
        line = line.strip()    
        match = re.match(r'(\w+)\s*=\s*(-?\d+)\s*,?[^<]*<\s*[-]?\d+\s*(.*)\*\/', line)
        if match:
            name, num, comment = match.groups()
            if int(num) < 0 :
                continue
            irqs[num] = {}
            irqs[num]["name"] = name
            irqs[num]["comment"] = comment.strip()
            pass

    return irqs

def ExtractStartS_CM4(compname,device_name,outputdir,svdpath,svdhpath,filever="V1.00",irqsum=32):
    
    irqs_dic = get_irqname_from_hfile(svdhpath)
    if len(irqs_dic) == 0 :
        print("[Error]Fail to get irq name!!!")
        exit(1)
    
    datestr = datetime.datetime.now().strftime("%#d. %B %Y")
    output_file = os.path.join(outputdir, f"startup_{device_name}.s")
    year = datetime.datetime.now().year
    res = []
    res.append(f""";/**************************************************************************//**
; * @file     startup_{device_name}.s
; * @brief    CMSIS Core Device Startup File for {device_name}.
; * @version  {filever}
; * @date     {datestr}
; *
; * @note
; *
; ******************************************************************************/
""")
    res.append(
    f""";/* Copyright (c) {year} {compname} LIMITED
;
;   All rights reserved.
;   Redistribution and use in source and binary forms, with or without
;   modification, are permitted provided that the following conditions are met:
;   - Redistributions of source code must retain the above copyright
;     notice, this list of conditions and the following disclaimer.
;   - Redistributions in binary form must reproduce the above copyright
;     notice, this list of conditions and the following disclaimer in the
;     documentation and/or other materials provided with the distribution.
;   - Neither the name of {compname} nor the names of its contributors may be used
;     to endorse or promote products derived from this software without
;     specific prior written permission.
;   *
;   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
;   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
;   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
;   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;   POSSIBILITY OF SUCH DAMAGE.
;   ---------------------------------------------------------------------------*/
;/*
;//-------- <<< Use Configuration Wizard in Context Menu >>> ------------------
;*/
    
    """)
    
    res.append(
    f"""

; <h> Stack Configuration
;   <o> Stack Size (in Bytes) <0x0-0xFFFFFFFF:8>
; </h>

Stack_Size      EQU     0x00000400

                AREA    STACK, NOINIT, READWRITE, ALIGN=3
Stack_Mem       SPACE   Stack_Size
__initial_sp


; <h> Heap Configuration
;   <o>  Heap Size (in Bytes) <0x0-0xFFFFFFFF:8>
; </h>

Heap_Size       EQU     0x00000C00

                AREA    HEAP, NOINIT, READWRITE, ALIGN=3
__heap_base
Heap_Mem        SPACE   Heap_Size
__heap_limit


                PRESERVE8
                THUMB


; Vector Table Mapped to Address 0 at Reset

                AREA    RESET, DATA, READONLY
                EXPORT  __Vectors
                EXPORT  __Vectors_End
                EXPORT  __Vectors_Size

__Vectors       DCD     __initial_sp              ; Top of Stack
                DCD     Reset_Handler             ; Reset Handler
                DCD     NMI_Handler               ; NMI Handler
                DCD     HardFault_Handler         ; Hard Fault Handler
                DCD     MemManage_Handler         ; MPU Fault Handler
                DCD     BusFault_Handler          ; Bus Fault Handler
                DCD     UsageFault_Handler        ; Usage Fault Handler
                DCD     0                         ; Reserved
                DCD     0                         ; Reserved
                DCD     0                         ; Reserved
                DCD     0                         ; Reserved
                DCD     SVC_Handler               ; SVCall Handler
                DCD     DebugMon_Handler          ; Debug Monitor Handler
                DCD     0                         ; Reserved
                DCD     PendSV_Handler            ; PendSV Handler
                DCD     SysTick_Handler           ; SysTick Handler

                ; External Interrupts

""")
    
    setdefaults = []
    setdefaultstr = "				Set_Default_Handler "
    DCD = r"                DCD     "
    irq_name = ""
    irq_num = ""
    irq_comment = ""
    for i in range(0, irqsum):
        num = str(i)
        if num in irqs_dic:
            irq_name = irqs_dic[num]['name'].replace("_IRQn", "_IRQHandler")
            irq_comment = irqs_dic[num]['comment']
        else:
            irq_name = str(0)
            irq_comment = "Reserved"
        
        irq_name = irq_name.ljust(30,' ')
        irq_num = str(num).rjust(3,' ')
        res.append(DCD + irq_name + ';'+ irq_num + ': ' + irq_comment + "\n")
        if num in irqs_dic:
            setdefaults.append(setdefaultstr + irq_name+ ';'+ irq_num + "\n")
    
    res.append(
    """__Vectors_End

__Vectors_Size  EQU     __Vectors_End - __Vectors

                AREA    |.text|, CODE, READONLY


; Reset Handler

Reset_Handler   PROC
                EXPORT  Reset_Handler             [WEAK]
                IMPORT  SystemInit
                IMPORT  __main
                LDR     R0, =SystemInit
                BLX     R0
                LDR     R0, =__main
                BX      R0
                ENDP

; Macro to define default exception/interrupt handlers.
; Default handler are weak symbols with an endless loop.
; They can be overwritten by real handlers.
                MACRO
                Set_Default_Handler  $Handler_Name
$Handler_Name   PROC
                EXPORT   $Handler_Name             [WEAK]
                B        .
                ENDP
                MEND

; Dummy Exception Handlers (infinite loops which can be modified)
				Set_Default_Handler NMI_Handler
				Set_Default_Handler HardFault_Handler
				Set_Default_Handler MemManage_Handler
				Set_Default_Handler BusFault_Handler
				Set_Default_Handler UsageFault_Handler
				Set_Default_Handler SVC_Handler
				Set_Default_Handler DebugMon_Handler
				Set_Default_Handler PendSV_Handler
				Set_Default_Handler SysTick_Handler


"""
    )
    res.append(''.join(setdefaults))        
    res.append(
     """                ALIGN


; User Initial Stack & Heap

                IF      :DEF:__MICROLIB

                EXPORT  __initial_sp
                EXPORT  __heap_base
                EXPORT  __heap_limit

                ELSE

                IMPORT  __use_two_region_memory
                EXPORT  __user_initial_stackheap

__user_initial_stackheap PROC
                LDR     R0, =  Heap_Mem
                LDR     R1, =(Stack_Mem + Stack_Size)
                LDR     R2, = (Heap_Mem +  Heap_Size)
                LDR     R3, = Stack_Mem
                BX      LR
                ENDP

                ALIGN

                ENDIF


                END
     """   
    )
    
    with open(output_file, "w") as f:
        f.write(''.join(res))
    
    print(f"{output_file} saved successfully.")
    

if __name__ == "__main__":
    
    compname = "RJMICRO"
    outputdir = ""
    svdpath = r"D:\Desktop\Spec2SVD\PySVDAssistant\Test\R2401.svd"
    svdhpath = r"D:\Desktop\Spec2SVD\PySVDAssistant\Test\R2401.h"
    device_name = 'R2401'
    
    ExtractStartS_CM4(compname,device_name,outputdir,svdpath,svdhpath)
    